package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Stock;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 师文明
 * @data 2024/12/23 下午3:11
 **/
public class getStockDayData2 {
    //创建一个固定大小的线程池
    // static ExecutorService executorService = Executors.newFixedThreadPool(50);

    public static int allup;
    public static double allupnum;
    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);

    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        return stocks;
    }

    public static void main(String[] args) throws Exception {

/*            int currentDay = 1;
            double sum=0;

            for(int num=0;num<5;num++){
                allup=0;
                allupnum=0;
                int num1=num;*/
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        for (Stock stock : stcokList) {
            //int finalNum = num+2;
            executorService.execute(() -> {
                try {
                    getData(stock.getCode(), stock.getType(), 2);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        Thread.sleep(30000);
              /*  double v=0;
                if(allup!=0){
                    v = allupnum / allup;
                }
                int week=1;
                while (num1>=5){
                    num1=num1-5;
                    week++;
                }

                System.out.println(("第"+week+"周 周"+(currentDay-num1)+" 日平均涨幅："+v+"\r\n"));
                sum+=v;*/
        //getData(stcokList.get(0).getCode(), stcokList.get(0).getType());
        // 关闭线程池，以优雅的方式
        executorService.shutdown();
/*            }
            System.out.println("总涨幅："+sum);
            System.out.println("平均涨幅："+sum/5);*/
    }

    public static void getData(String code, int type, int num) throws Exception {
        // 连接到新浪财经接口
        String url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f116,f117&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&rtntype=6&secid=" + type + "." + code + "&klt=101&fqt=1";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
        // 从数据源获取实时股票数据
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String data = response.toString();
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            String name = jsonObject1.get("name").toString();
            JSONArray klines = JSONArray.parse(jsonObject1.get("klines").toString());
            double price0 = Double.parseDouble(klines.get(klines.size() - 1).toString().split(",")[2]);
            if (klines.size() > 30) {
                //           开     收盘   最高 最低     成交额  成交量     振幅  涨跌幅  涨跌额  换手率  市盈率
                // 2025-03-21,75.60,71.77,76.22,71.77,36859,270881026.00,5.82,-6.17,-4.72,13.41
                // int num=5;
               /* double max=0;
                double min=1000000000;
                double average=0;
                double total=0;

                double maxprice=0;
                double minprice=10000;
                //一个月振幅
                for(int i=(num+1);i<(num+11);i++){
                    String[] split = klines.get(klines.size() - i).toString().split(",");
                    double price = Double.parseDouble(split[2]);
                    maxprice= Math.max(price, maxprice);
                    minprice= Math.min(price, minprice); minprice = price < minprice ? price : min;
                }
                double priceDiff  = (maxprice - minprice) / price0;

                for(int i=(num+1);i<(num+10);i++){
                    String[] split = klines.get(klines.size() - i).toString().split(",");
                    double money = Double.parseDouble(split[5]);
                    max= Math.max(money, max);
                    min= Math.min(money, min);
                    total+=money;
                }
                average=total/9;
                //十天内成交量振幅
                double v3 = (max - min) / average;*/

                //昨日成交额
                double v = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[5]);
                //前天成交额
                double v1 = Double.parseDouble(klines.get(klines.size() - (num + 1)).toString().split(",")[5]);
                //昨日涨幅
                double v2 = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[8]);
                //今日涨幅
                double v4 = Double.parseDouble(klines.get(klines.size() - num + 1).toString().split(",")[8]);
                //昨日收盘
                double v8 = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[2]);

                //放量2倍以上 涨幅大于0小于4  一个月内振幅小于10
                if (/*v/v1>2 &&*/ v2 > 3 && v2 < 5 /*&&v3<1*/ /*&&priceDiff<0.1*/) {
                    String url1 = "https://51.push2.eastmoney.com/api/qt/stock/sse?fields=f31,f50,f71,f116,f117,f168&secid=" + type + "." + code;

                    JSONObject webData = getWebData(url1);
                    //市值
                    Double v5 = Double.parseDouble(webData.get("f117").toString()) / 100000000;
                    //量比
                    Double v6 = Double.parseDouble(webData.get("f50").toString()) / 100;
                    //换手率
                    Double v7 = Double.parseDouble(webData.get("f168").toString()) / 100;

                    Double v9 = Double.parseDouble(webData.get("f71").toString()) / 100;

                    //市值大于50亿 小于200亿   量比大于1  换手率大于5小于10  收盘高于平均价
                    if (!name.startsWith("ST") && !name.startsWith("*ST") && v5 > 50 && v5 < 200 && v6 > 1 && v7 > 5 && v7 < 10 && v9 > v8) {
                        System.out.println(name + "  ：" + v4);
                        allupnum += v4;
                        allup++;
                    }
                }
            }
        }
    }

    public static JSONObject getWebData(String url) {
        URL obj = null;
        JSONObject jsonObject1;
        try {
            obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", "qgqp_b_id=0c801f7a5b2dbbe1a7578a4f50bf5c81; websitepoptg_api_time=1742518229630; st_si=94336787243959; fullscreengg=1; fullscreengg2=1; st_asi=delete; HAList=ty-1-688395-%u6B63%u5F26%u7535%u6C14%2Cty-0-920128-%u80DC%u4E1A%u7535%u6C14; st_pvi=35314926305263; st_sp=2025-03-21%2008%3A50%3A29; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=12; st_psi=20250321164157298-111000300841-7480637044");
            // 从数据源获取实时股票数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
                break;
            }
            in.close();
            String data = response.toString();
            String[] split = data.split("data:");
            JSONObject jsonObject = JSONObject.parseObject(split[1]);
            jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            //s = split[1].split("}}")[0];

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject1;
    }
}

